package user_logic

import (
	"context"
	"database/sql"
	"errors"
	"fmt"

	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

type QueryUserInfo struct {
	ID         int            `db:"id" json:"id"`
	Username   string         `db:"username" json:"username"`
	Role       string         `db:"role" json:"role"`
	Email      sql.NullString `db:"email" json:"email"`
	Department sql.NullString `db:"department" json:"department"`
	CreatedAt  string         `db:"created_at" json:"createdAt"`
	UpdatedAt  string         `db:"updated_at" json:"updatedAt"`
}

// NewQueryUserLogic 查询用户
func NewQueryUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryUserLogic {
	return &QueryUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *QueryUserLogic) QueryUser(req *types.GetUserRequest) (resp *types.UserResponse, err error) {
	var query string

	var users []types.UserInfo
	var userInfos []QueryUserInfo

	// 判断使用的数据库类型
	flag := l.svcCtx.Config.UseMysql

	if req.Username == "*" {
		// 查询所有用户
		if flag {
			query = fmt.Sprintf("SELECT id, username, role, email, department, created_at, updated_at FROM %s WHERE deleted_at IS NULL",
				l.svcCtx.Config.Mysql.Tables.UserInfoTable)
		} else {
			query = fmt.Sprintf("SELECT id, username, role, email, department, created_at, updated_at FROM %s WHERE deleted_at IS NULL",
				l.svcCtx.Config.SQLite.Tables.UserInfoTable)
		}

		// 执行查询
		err = l.svcCtx.Conn.QueryRows(&userInfos, query)
		if err != nil {
			return nil, fmt.Errorf("failed to query users: %v", err)
		}
	} else {
		// 验证输入数据
		if req.Username == "" {
			return &types.UserResponse{
				Code:    500,
				Message: "用户名不能为空"}, fmt.Errorf("用户名不能为空")
		}

		// 查询特定用户
		if flag {
			query = fmt.Sprintf("SELECT id, username, role, email, department, created_at, updated_at FROM %s WHERE username = ? AND deleted_at IS NULL",
				l.svcCtx.Config.Mysql.Tables.UserInfoTable)
		} else {
			query = fmt.Sprintf("SELECT id, username, role, email, department, created_at, updated_at FROM %s WHERE username = ? AND deleted_at IS NULL",
				l.svcCtx.Config.SQLite.Tables.UserInfoTable)
		}

		// 执行查询
		err = l.svcCtx.Conn.QueryRows(&userInfos, query, req.Username)
		if err != nil {
			if errors.Is(err, sql.ErrNoRows) {
				return &types.UserResponse{
					Code:    500,
					Message: "用户不存在"}, fmt.Errorf("user not found")
			}
			return nil, fmt.Errorf("failed to query user: %v", err)
		}
	}

	for _, info := range userInfos {
		users = append(users, types.UserInfo{
			ID:         info.ID,
			Username:   info.Username,
			Role:       info.Role,
			Email:      info.Email.String,
			Department: info.Department.String,
			CreatedAt:  info.CreatedAt,
			UpdatedAt:  info.UpdatedAt,
		})
	}

	return &types.UserResponse{
		Code:    200,
		Message: "获取用户信息成功",
		Data:    users,
	}, nil
}
